<template>
  <div>
    <Modal
      v-model="trans"
      title="调整表头显示字段及排序"
      @on-cancel="editDisplayFieldCancel('0')"
      width="566"
      :footer-hide="true"
      :mask-closable="false"
      class="subscribeModalStyle"
    >
      <div class="transferBox">
        <div class="sourcedataBox">
          <div class="sourcedataBoxTit">
            <input
              :disabled="sourceList.length == 0"
              type="checkbox"
              id="sourceListLabel"
              @click="toggleAll(0)"
              :checked="selectedAllStatus(0)"
            />
            <label for="sourceListLabel">未在表头中显示({{sourceList.length}})</label>
          </div>

          <div class="sourcedataCon">
            <ul>
              <li v-for="item in sourceList">
                <input
                  type="checkbox"
                  :id="item.dbKey"
                  v-model="item.isSelected"
                />
                <label :for="item.dbKey">{{ item.fieldValue }}</label>
              </li>
            </ul>
          </div>
        </div>

        <div class="btnBox">
          <div class="btnBoxCenter">
            <span
              @click="toTarget"
              :class="[
                sourceList.length != 0 && sourceRefNum != 0
                  ? 'active'
                  : 'disabled',
                'ty-transfer-btn-toright to-switch',
              ]"
            >
              <Button
                type="primary"
                :disabled="
                  sourceList.length != 0 && sourceRefNum != 0 ? false : true
                "
                ><Icon type="ios-arrow-forward"
              /></Button>
            </span>
            <span
              @click="toSource"
              :class="[
                targetList.length != 0 && targetRefNum != 0
                  ? 'active'
                  : 'disabled',
                'ty-transfer-btn-toleft to-switch',
              ]"
            >
              <Button
                type="primary"
                :disabled="
                  targetList.length != 0 && targetRefNum != 0 ? false : true
                "
                ><Icon type="ios-arrow-back"
              /></Button>
            </span>
          </div>
        </div>

        <div class="sourcedataBox">
          <div class="sourcedataBoxTit">
            <input
              :disabled="targetList.length == 0"
              type="checkbox"
              @click="toggleAll(1)"
              :checked="selectedAllStatus(1)"
            />
            <label for="sourceListLabel">已在表头中显示({{targetList.length}})</label>
          </div>

          <div class="sourcedataCon">
            <ul>
              <li v-for="(item, index) in targetList">
                <input
                  type="checkbox"
                  :disabled="item.dbKey=='customer_phone'||item.dbKey=='customer_name'||item.dbKey=='attribution_consultant'"
                  :class="item.dbKey=='customer_phone'||item.dbKey=='customer_name'||item.dbKey=='attribution_consultant' ? 'notCursor' : ''"
                  :id="item.dbKey"
                  v-model="item.isSelected"
                />
                <label
                  :for="item.dbKey"
                  :class="item.dbKey=='customer_phone'||item.dbKey=='customer_name'||item.dbKey=='attribution_consultant' ? 'notCursor' : ''"
                  >{{ item.fieldValue }}</label
                >
                <div class="upDown" v-if="item.dbKey!=='customer_phone'&&item.dbKey!=='customer_name'&&item.dbKey!=='attribution_consultant'">
                  <span
                    @click="upItems(index)"
                    :class="[
                      targetList.length != 0 && targetRefNum != 0
                        ? 'active'
                        : 'disabled',
                      'ty-transfer-btn-totop to-switch',
                    ]"
                    ><Icon
                      type="md-arrow-round-up"
                      :disabled="true"
                      size="20"
                      :color="index == 3 ? '#c5c8ce' : '#2d8cf0'"
                      
                  /></span>
                  <span
                    
                    @click="downItems(index)"
                    :class="[
                      targetList.length != 0 && targetRefNum != 0
                        ? 'active'
                        : 'disabled',
                      'ty-transfer-btn-tobottom to-switch',
                    ]"
                    ><Icon
                      
                      type="md-arrow-round-down"
                      size="20"
                      :color="
                        index == targetList.length - 1 ? '#c5c8ce' : 'red'
                      "
                  /></span>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="explain">
        <span> 说明：您可点击箭头，调整字段在表头中显示的位置</span>
      </div>
      <div class="transferFooter">
        <Button @click="editDisplayFieldCancel('1')">取消</Button>
        <Button type="info" @click="editDisplayFieldSave">保存</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { customerHeadUpdate } from "@/api/customerManagement.js";
export default {
  props: ["sourcedata", "targetdata", "transforFlag"],

  data() {
    return {
      trans:this.transforFlag,
      sourceList: [],
      targetList: [],
      toTargetFlag: true,
      toSourceFlag: true,

      updateInfo: [],
    };
  },
  created() {
    console.log(this.targetdata, "this.targetdata");
    // if(this.targetdata===null||this.targetdata.length===0){
    //         this.sourceList = this.formatData(val);
    //         return;
    //     }
    //     var source=[];
    //     var target=this.targetdata;
    //     this.sourcedata.forEach(function (item) {
    //         let data = target.filter(n => n.name==item.name);
    //         if(data==null||data.length==0){
    //             source.push(item);
    //         }
    //     })
    //     this.sourceList = this.formatData(source);
    //     this.targetList = this.formatData(this.targetdata);
  },
  computed: {
    // 源数据中选中的数量
    sourceRefNum() {
      return this.sourceList.filter((item) => item.isSelected).length;
    },
    // 目标数据中选中的数量
    targetRefNum() {
      return this.targetList.filter((item) => item.isSelected).length;
    },
    // 选择的源记录数量
    selectSourceItemNumber() {
      return this.sourceList.filter((item) => item.isSelected).length;
    },
    // 选择目标记录数量
    selectTargetItemNumber() {
      return this.targetList.filter((item) => item.isSelected).length;
    },
  },
  methods: {
    // 编辑表头显示不显示
    editDisplayFieldSave() {
      console.log(this.targetList, this.sourceList, "结果啊这是");
      this.targetList.forEach((item, index) => {
        this.updateInfo.push({
          dbKey: item.dbKey,
          serialNo: index,
        });
      });
      this.reCustomerHeadUpdate();
    },
    // 保存修改的表头
    reCustomerHeadUpdate() {
      let params = {
        buildingId: Number(JSON.parse(this.$tool.getStorage("caseBuildingId"))),
        updateInfo: this.updateInfo,
      };
      customerHeadUpdate(params)
        .then((res) => {
          console.log("编辑表头成功", res);
          this.$emit("headupdata");
          // this.$emit("okFilterFun", "");
          this.updateInfo=[];
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },

    formatData(dataList) {
      let data = dataList.map((item) => {
        return {
          ...item,
          isSelected: false,
        };
      });
      return data;
    },
    moveItems(direction) {
      // let selectedItem = this.targetList.filter((item) => item.isSelected).map((item) => {
      //     return item.name;
      //   });
      if (direction == 1) {
        //下移
        for (var i = selectedItem.length - 1; i >= 0; i--) {
          let index = this.targetList
            .map((item) => {
              return item.name;
            })
            .indexOf(selectedItem[i]);
          if (index >= this.targetList.length - 1) return;
          this.targetList[index] = this.targetList.splice(
            index + 1,
            1,
            this.targetList[index]
          )[0];
        }
      }
      if (direction == 0) {
        //上移
        for (var i = 0; i < selectedItem.length; i++) {
          let index = this.targetList
            .map((item) => {
              return item.name;
            })
            .indexOf(selectedItem[i]);
          if (index <= 0) return;
          this.targetList[index] = this.targetList.splice(
            index - 1,
            1,
            this.targetList[index]
          )[0];
        }
      }
      // if (direction == 3) {
      //   //置底
      //   for (var i = 0; i < selectedItem.length; i++) {
      //     let index = this.targetList
      //       .map((item) => {
      //         return item.name;
      //       })
      //       .indexOf(selectedItem[i]);
      //     if (index >= this.targetList.length - 1) return;
      //     this.targetList.push(this.targetList[index]);
      //     this.targetList.splice(index, 1);
      //   }
      // }
      // if (direction == 4) {
      //   //置顶
      //   for (var i = selectedItem.length - 1; i >= 0; i--) {
      //     let index = this.targetList
      //       .map((item) => {
      //         return item.name;
      //       })
      //       .indexOf(selectedItem[i]);
      //     if (index <= 0) return;
      //     this.targetList.unshift(this.targetList[index]);
      //     this.targetList.splice(index + 1, 1);
      //   }
      // }
    },
    upItems(index) {
      if (index > 3) {
        let update = this.targetList[index - 1];
        this.targetList.splice(index - 1, 1);
        this.targetList.splice(index, 0, update);
      } else {
        this.$Message.warning("已不可上移!");
      }
    },

    downItems(index) {
      if (index + 1 != this.targetList.length) {
        let downdate = this.targetList[index + 1];
        this.targetList.splice(index + 1, 1);
        this.targetList.splice(index, 0, downdate);
      } else {
        this.$Message.warning("已经是最后一条，不可下移!");
      }
    },

    exchange(fd, td) {
      let selectedItem = fd
        .filter((item) => item.isSelected)
        .map((item) => {
          return {
            ...item,
            isSelected: false,
          };
        });
      td.push(...selectedItem);
      var selectedlist = fd.filter((item) => !item.isSelected);
      return selectedlist;
    },
    // 全选状态
    selectedAllStatus(type) {
      if (type == 0) {
        if (
          this.selectSourceItemNumber === this.sourceList.length &&
          this.selectSourceItemNumber !== 0
        ) {
          return true;
        } else {
          return false;
        }
      } else {
        if (
          // this.selectTargetItemNumber === this.targetList.length && this.selectTargetItemNumber !== 0
          this.selectTargetItemNumber+3 != this.targetList.length
        ) {
          return false;
        } else {
          return true;
        }
      }
    },
    // 全选及反选
    toggleAll(type) {
      if (type == 0) {
        let len = this.sourceList.length;
        let slen = this.sourceList.filter((item) => item.isSelected).length;
        if (len != slen) {
          this.sourceList.map((item) => (item.isSelected = true));
        } else {
          this.sourceList.map((item) => (item.isSelected = false));
        }
      } else {
        let len = this.targetList.length;
        let slen = this.targetList.filter((item) => item.isSelected).length;
        console.log(len,"this.targetList.length",slen,'chooseLength');

        if (len != slen+3) {
          this.targetList.map(item => {
              if(item.dbKey!='customer_phone'&&item.dbKey!='customer_name'&&item.dbKey!='attribution_consultant'){
                item.isSelected = true
              }
            } 
          );
        } else {
          this.targetList.map((item) => (item.isSelected = false));
        }
      }
    },
    // 把选择数据转移到目标（右框）
    toTarget() {
      this.sourceList = this.exchange(this.sourceList, this.targetList);
    },
    // 把选择数据转回到源（左框）
    toSource() {
      this.targetList = this.exchange(this.targetList, this.sourceList);
    },

    //自定义table头部菜单配置 关闭
    editDisplayFieldCancel(val) {
      // this.options.type = "";
      this.targetList = this.formatData(this.targetdata);
      this.sourceList = this.formatData(this.sourcedata);
      this.$emit("fieldCancel");
    },

  },
  mounted() {},
  watch: {
    transforFlag(val){
      this.trans = val
    },

    sourcedata(val) {
      this.sourceList = this.formatData(val);
      console.log(this.sourceList, "未显示list");
    },

    targetdata(val) {
      //显示
      this.targetList = this.formatData(val);
      this.targetList.forEach((item,index) => {
        if(item.dbKey=="customer_name"){
          let arr = this.targetList.splice(index,1);
          this.targetList.unshift(...arr)
        }
        if(item.dbKey=="customer_phone"){
          let arr = this.targetList.splice(index,1);     
          this.targetList.splice(1,0,...arr);
        }
        if(item.dbKey=="attribution_consultant"){
          let arr = this.targetList.splice(index,1);     
          this.targetList.splice(2,0,...arr);
        }
      });
      console.log(this.targetList, "显示list");
    },
  },
};
</script>
<style lang="scss" scoped>
.transferBox {
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .sourcedataBox {
    border: 1px solid #e8eaec;
    flex: 3;
    .sourcedataBoxTit {
      // display: flex;
      // flex-direction: row;
      background: #f9fafc;
      // padding: 8px 16px;
      // cursor: pointer;
      margin: 0;
      line-height: normal;
      padding: 7px 16px;
      clear: both;
      color: #515a6e;
      font-size: 14px !important;
      white-space: nowrap;
      list-style: none;
      cursor: pointer;
      // input {
      //   display: inline-block;
      // }
      label {
        margin: 0 4px;
        vertical-align: 2px;
        font-size: 15px;
      }
    }
    .sourcedataCon {
      height: 460px;
      overflow-y: scroll;
      ul > li {
        margin: 0;
        line-height: normal;
        padding: 7px 16px;
        clear: both;
        color: #515a6e;
        font-size: 14px !important;
        white-space: nowrap;
        list-style: none;
        display: flex;
        flex-direction: row;
        input {
          margin-top: 4px;
          cursor: pointer;
        }
        label {
          margin: 0 4px;
          cursor: pointer;
          width: 100px;
        }
        .upDown {
          cursor: pointer;
        }
      }
    }
  }
  .btnBox {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 500px;
    .btnBoxCenter {
      display: flex;
      flex-direction: column;
      align-items: center;
      span {
        margin: 10px;
      }
    }
  }
}
.transferFooter {
  margin-top: 20px;
  text-align: center;
  button {
    width: 80px;
    margin: 0 10px;
  }
}
.notCursor {
  color: #c5c8ce;
  cursor: not-allowed !important;
}
.notClick {
  pointer-events: none;
}
.explain {
  overflow: hidden;
  span {
    margin-top:8px;
    float:right;
    width: 230px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }
}
</style>

